<?php
namespace fast;
class Async{
	private static $hook_list = array();
    private static $hooked = false;
    /**
     * hook函数fastcgi_finish_request执行
     * 
     * @param callback $callback
     * @param array $params
     */
    public static function hook($callback, $params) {
        self::$hook_list[] = array('callback' => $callback, 'params' => $params);
        if(self::$hooked == false) {
            self::$hooked = true;
            register_shutdown_function(array(__CLASS__, '__run'));
        }
    }
    /**
     * 由系统调用
     * 
     * @return void
     */
    public static function __run() {
        // if(function_exists("fastcgi_finish_request")){
        // 	fastcgi_finish_request();
        // 	if(empty(self::$hook_list)) {
	       //      return;
	       //  }
	       //  foreach(self::$hook_list as $hook) {
	       //      $callback = $hook['callback'];
	       //      $params = $hook['params'];
	       //      call_user_func_array($callback, $params);
	       //  }
        // }else{ //其他的模式
        // 	foreach(self::$hook_list as $hook) {
	       //      $callback = $hook['callback'];
	       //      $params = $hook['params'];
	       //      if(is_string($callback)){
	       //      	self::socket($callback,$params);
	       //      }
	       //  }
        // }
        foreach(self::$hook_list as $hook) {
            $callback = $hook['callback'];
            $params = $hook['params'];
            if(is_string($callback)){
                self::socket($callback,$params);
            }
        }
        
    }
    public static function socket($action,$params){
    	$errno = $errstr = null;
    	$params = json_encode($params);
    	try{
            $scheme = '';
            if(request()->isSsl()){
                $scheme = "ssl://";
            }
    		$sock = fsockopen($scheme.request()->host(), request()->port(), $errno, $errstr, 5);
    		if (!$sock) {
			   return false;
			} else {
			    fwrite($sock, "POST ".request()->domain()."/api/async/".$action." HTTP/1.1\r\n");
			    fwrite($sock, "Host: ".request()->host()."\r\n");
			    fwrite($sock, "Content-length: ".mb_strlen($params)."\r\n");
			    fwrite($sock, "Content-type: application/json\r\n");
			    fwrite($sock, "Accept: */*\r\n");
			    fwrite($sock, "\r\n");
			    fwrite($sock, $params."\r\n");
			    fwrite($sock, "\r\n");
                fwrite($sock, "Connection: Close\r\n\r\n");
                // $html = '';
                // $content = '';
                // while (!feof($sock))
                // {
                //     $content .= fgets($sock);
                // }
                // file_put_contents('/var/www/html/AHL/public/uploads/22222.log', $content);
			    fclose($sock);
			}
    	}catch(\think\exception\ErrorException $e){
    		//echo $e->getMessage();
    		return false;
    	}
    	
		return true;
    }
} 
/**调用方式**/
//Async::hook(array($this, 'sendEmail'), array());//面向对象调用
